package com.jlju.djmhadmin.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jlju.djmhadmin.common.GenericResponse;
import com.jlju.djmhadmin.common.util.JsonUtil;
import com.jlju.djmhadmin.common.util.RequiredStringValidator;
import com.jlju.djmhadmin.common.util.StringUtils;
import com.jlju.djmhadmin.common.util.Validations;
import com.jlju.djmhadmin.dao.common.util.UUIDUtils;
import com.jlju.djmhadmin.dao.entity.Notice;
import com.jlju.djmhadmin.dao.entity.Student;
import com.jlju.djmhadmin.dao.entity.User;
import com.jlju.djmhadmin.dao.service.JobService;
import com.jlju.djmhadmin.dao.service.NoticeService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * All rights Reserved, Designed By Liting.
 *
 * @description: 求职相关controller
 * @author: LiTing[liting08011@163.com]
 * @create: 2018-04-19 17:52
 * @Copyright ©2018 Liting. All rights reserved.
 * 注意：本内容仅限于吉林建筑大学ACM协会内部传阅，禁止外泄以及用于其他的商业用途。
 **/
@RestController
@Slf4j
@RequestMapping("/notice")
public class NoticeController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private NoticeService noticeService;


    @ApiOperation("新增公告")
    @RequestMapping(value = "/add")
    @Validations(requiredStrings={
            @RequiredStringValidator(fieldName="title",errCode="ACM0600",errMsg="请求参数不足,标题不能为空"),
            @RequiredStringValidator(fieldName="content",errCode="ACM0601",errMsg="请求参数不足，内容不能为空"),
            @RequiredStringValidator(fieldName="author",errCode="ACM0602",errMsg="请求参数不足，作者不能为空"),
            @RequiredStringValidator(fieldName="type",errCode="ACM0603",errMsg="请求参数不足，类型不能为空")
    })
    public Callable<GenericResponse<String>> add(@RequestBody String json) {
        logger.info("***新闻公告添加开始***");
        try {
            Notice notice = JsonUtil.jsonToObject(json,Notice.class);
            notice.setUuid(UUIDUtils.getUuid());
            notice.setPublishDate(new Date().toString());
            notice.setStatus("1");
            notice.setAuthor("aaaaa");
            this.noticeService.add(notice);
            logger.info("***新闻公告添加成功***");
            return () -> GenericResponse.success("ACM0008", "添加成功", notice);
        } catch (Exception e) {
            logger.error("***新闻公告添加失败***" + e);
            return () -> GenericResponse.failed("ACM0009", "添加失败");
        }
    }

    @RequiredStringValidator(fieldName="uuid",trim=true,errCode="ACM0604",errMsg="请求参数不足,公告编号不能为空")
    @ApiOperation("删除公告")
    @RequestMapping(value = "/delete")
    public Callable<GenericResponse<String>> delete(@RequestBody String json, HttpSession session) {
        logger.info("***新闻公告删除开始***入参：" + json);
        try {
            if("2".equals(session.getAttribute("type"))){
                throw new Exception("对不起，您无操作权限");
            }
            json = StringUtils.trimFirstAndLastChar(json,'\"');
            Notice notice = new Notice(json);
            notice.setStatus("0");
            this.noticeService.deleteById(notice);
            logger.info("***新闻公告删除成功***");
            return () -> GenericResponse.success("ACM0300", "删除成功", notice);
        } catch (Exception e) {
            logger.info("***新闻公告删除失败***" + e);
            return () -> GenericResponse.failed("ACM0301", "删除失败");
        }
    }

    @RequiredStringValidator(fieldName="uuid",trim=true,errCode="ACM0604",errMsg="请求参数不足,公告编号不能为空")
    @ApiOperation("更新公告")
    @RequestMapping(value = "/update")
    public Callable<GenericResponse<String>> update(@RequestBody String json, HttpSession session) {
        logger.info("***新闻公告更新开始***入参：" + json);
        try {
            if("2".equals(session.getAttribute("type"))){
                throw new Exception("对不起，您无操作权限");
            }
            Notice notice = JsonUtil.jsonToObject(json,Notice.class);
            this.noticeService.updateById(notice);
            logger.info("***新闻公告更新成功***");
            return () -> GenericResponse.success("ACM0014", "更新成功", notice);
        } catch (Exception e) {
            logger.error("***新闻公告更新失败***" + e);
            return () -> GenericResponse.failed("ACM0015", "更新失败");
        }
    }

    @ApiOperation("查看全部新闻，带分页")
    @RequestMapping(value = "/findAll")
    public Callable<GenericResponse<List<Notice>>> findAll(Notice notice) {
        logger.info("***查看全部新闻信息（分页）***");
        try {
//            Notice notice = JsonUtil.jsonToObject(json,Notice.class);
//            PageHelper.startPage(pageNum, pageSize);
            List<Notice> list = this.noticeService.findAll(notice);
            // 用PageInfo对结果进行包装
//            PageInfo<Notice> pageInfo = new PageInfo<Notice>(list);
            logger.info("***查看全部新闻信息（分页） 成功***");
            return () -> GenericResponse.success("ACM0010", "查询成功", list);
        } catch (Exception e) {
            logger.info("***查看全部新闻信息（分页）失败***" + e);
            return () -> GenericResponse.failed("ACM0011", "查询失败");
        }
    }

    @ApiOperation("查看详细新闻信息")
    @RequestMapping(value = "/findOneById")
    public Callable<GenericResponse<String>> findOneById(String uuid) {
        logger.info("***新闻信息查询开始***");
        try {
//            Notice notice = JsonUtil.jsonToObject(json,Notice.class);
            Notice finalNotice = this.noticeService.findOneById(uuid);
            logger.info("***新闻信息详情查询成功***" + finalNotice);
            return () -> GenericResponse.success("ACM0012", "详细查询成功", finalNotice);
        } catch (Exception e) {
            logger.error("新闻信息详情查询失败" + e);
            return () -> GenericResponse.failed("ACM0013", "查询详情失败");
        }
    }

    @ApiOperation("查看全部新闻，带分页,后台使用")
    @RequestMapping(value = "/findAdmin")
    public Callable<GenericResponse<List<Notice>>> findAdmin(@RequestBody String json, int pageNum, int pageSize) {
        logger.info("***查看全部新闻信息（分页）***");
        try {
            Notice notice = JsonUtil.jsonToObject(json,Notice.class);
            PageHelper.startPage(pageNum, pageSize);
            List<Notice> list = this.noticeService.findAll(notice);
            // 用PageInfo对结果进行包装
            PageInfo<Notice> pageInfo = new PageInfo<Notice>(list);
            logger.info("***查看全部新闻信息（分页） 成功***");
            return () -> GenericResponse.success("ACM0010", "查询成功", list);
        } catch (Exception e) {
            logger.info("***查看全部新闻信息（分页）失败***" + e);
            return () -> GenericResponse.failed("ACM0011", "查询失败");
        }
    }

}